package top.infopub.mgr.cap.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.cap.PayInterestDto;
import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.cap.PayIntDetTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.cap.dao.PayInterestDao;
import top.infopub.mgr.cap.dao.PayInterestDetailDao;
import top.infopub.mgr.cap.domain.PayInterestDomain;
import top.infopub.mgr.cap.jsonvo.PayInterestJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.PayInterestService;
import top.infopub.mgr.cap.vo.PayInterestQuery;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.util.DateUtils;
import top.infopub.model.cap.CapProcessDetail;
import top.infopub.model.cap.PayIntBankInfo;
import top.infopub.model.cap.PayInterest;
import top.infopub.model.cap.PayInterestDetail;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.util.Date;
import java.util.List;

@Service
public class PayInterestServiceImpl extends GenericServiceImpl<PayInterest, String> implements
		PayInterestService {

	@Autowired
	private PayInterestDao payInterestDao;

	@Autowired
	private PayInterestDetailDao payInterestDetailDao;

	@Autowired
	private ProjectAttachmentDao projectAttachmentDao;

	@Autowired
	private SetupProService setupProService;

	@Autowired
	private OAFlowService oaFlowService;

	@Autowired
	private CapProcessManageService capProcessManageService;
	
	@Override
	public GenericDao<PayInterest, String> getDao() {
		return payInterestDao;
	}

	@Override
	public PageInfo<PayInterestDomain> queryPayInterestPage(ParamPage paramPage, PayInterestQuery query) {
		if (StringUtils.isNotBlank(query.getDates())) {
			String[] dateArr = query.getDates().split("~");
			try {
				query.setStartDate(DateUtils.parseDateByFormat(dateArr[0], DateUtils.YYYY_MM_DD));
				if (dateArr.length > 1) {
					query.setEndDate(DateUtils.parseDateByFormat(dateArr[1], DateUtils.YYYY_MM_DD));
				}
			} catch (Exception e) {}
		}
		PageHelper.startPage(paramPage.getPage(), paramPage.getLimit());
		List<PayInterestDomain> list = payInterestDao.queryPayInterestList(query);
		PageInfo<PayInterestDomain> pageInfo = new PageInfo<PayInterestDomain>(list);
		return pageInfo;
	}

	@Override
	public PayInterestJsonVo queryDetailById(String id) {
		PayInterestJsonVo payIntJson = new PayInterestJsonVo();
		//基础信息
		PayInterestDto payInterDto = payInterestDao.queryDetailById(id);
		payIntJson.setInfo(payInterDto);

		//详情表格信息
		List<PayInterestDetail> detailList = payInterestDetailDao.queryListByPayIntId(payInterDto.getId());
		payIntJson.setDetailList(detailList);

		//银行列表
		List<PayIntBankInfo> bankInfoList = payInterestDao.queryPayIntBankInfoList();
		payIntJson.setBankInfoList(bankInfoList);

		//附件信息表
		List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(payInterDto.getId(), ProjectFileTypeEnum.FILE_TYPE56.getCode(), null);
		payIntJson.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
		return payIntJson;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public RspVo edit(PayInterestDto payInterDto, List<PayInterestDetail> detailList,
					  List<ProjectAttachment> attachmentList, Integer submitType, AuthorizationVO vo) {
		//校验融资付息数据是否存在
		PayInterest tmpPi = payInterestDao.selectByPrimaryKey(payInterDto.getId());
		if (tmpPi == null) return RspVo.getFailureResponse(400, "融资付息数据不存在");
		//判断审批状态
		if (StringUtils.isNotBlank(tmpPi.getProcessStatus())
				&& (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpPi.getProcessStatus())
				|| StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpPi.getProcessStatus()))) {
			return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
		}

		PayInterest payInterest = new PayInterest();
		payInterest.setId(tmpPi.getId());
		payInterest.setUptBy(vo.getId());
		payInterest.setUptTime(new Date());
		payInterest.setPayIntAmt(payInterDto.getPayIntAmt());
//		payInterest.setPaymentStatus("1");
//		payInterest.setBankName(payInterDto.getBankName());
//		payInterest.setAccountNo(payInterDto.getAccountNo());
//		payInterest.setPaymentDate(payInterDto.getPaymentDate());
//		payInterest.setActualPayAmt(payInterDto.getActualPayAmt());
		//更新融资付息主表信息
		payInterestDao.updateByIdSelective(payInterest);

		//更新子表数据，类型为3的更新
		if (detailList != null && detailList.size() > 0) {
			for (PayInterestDetail pid : detailList) {
				if (pid == null) continue;
				if (StringUtils.equals(PayIntDetTypeEnum.PAY_INT_DET_TYPE3.getCode(), pid.getTypes())) {
					//新放款数据可编辑
					payInterestDetailDao.updateByIdSelective(pid);
				}
			}
		}

		//检查银行卡号是否存在，不存在保存到融资付息银行卡信息中
//		PayIntBankInfo pibi = payInterestDao.queryByAccountNo(payInterest.getAccountNo());
//		if (pibi == null) {
//			pibi = new PayIntBankInfo();
//			pibi.setCodes(IdFactory.getUUIDUpper());
//			pibi.setAccountNo(payInterest.getAccountNo());
//			pibi.setBankName(payInterest.getBankName());
//			pibi.setStatus("1");
//			pibi.setAddBy(vo.getCode());
//			pibi.setAddTime(new Date());
//			payInterestDao.insertPayIntBankInfo(pibi);
//		}

		//更新附件信息
		projectAttachmentDao.deleteByWhere(tmpPi.getId(), ProjectFileTypeEnum.FILE_TYPE56.getCode(), null);
		if (attachmentList != null && attachmentList.size() > 0) {
			projectAttachmentDao.insertBatch(attachmentList);
		}

		if (submitType == 1) {
			if (org.apache.commons.lang.StringUtils.isNotBlank(tmpPi.getOaId())) {
				oaFlowService.finishOA(tmpPi.getOaId());
			}
			PayInterestJsonVo payIntJson = queryDetailById(tmpPi.getId());
			payIntJson.setBankInfoList(null);
			String detailJson = JSON.toJSONString(payIntJson);
			capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE18, detailJson, tmpPi.getId(), tmpPi.getProCode(), vo);
		}
		return RspVo.getSuccessResponse();
	}

	@Override
	public RspVo modifyFinInfo(PayInterest payInterest, AuthorizationVO vo, String processId) {
		//校验融资付息数据是否存在
		PayInterest tmpPi = payInterestDao.selectByPrimaryKey(payInterest.getId());
		if (tmpPi == null) return RspVo.getFailureResponse(400, "融资付息数据不存在");
		//判断审批状态
		if (!(StringUtils.isNotBlank(tmpPi.getProcessStatus())
				&& StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpPi.getProcessStatus()))) {
			return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
		}

		payInterest.setUptBy(vo.getId());
		payInterest.setUptTime(new Date());
		payInterest.setPaymentStatus("1");
		//更新融资付息主表信息
		payInterestDao.updateByIdSelective(payInterest);

		//检查银行卡号是否存在，不存在保存到融资付息银行卡信息中
		PayIntBankInfo pibi = payInterestDao.queryByAccountNo(payInterest.getAccountNo());
		if (pibi == null) {
			pibi = new PayIntBankInfo();
			pibi.setCodes(IdFactory.getUUIDUpper());
			pibi.setAccountNo(payInterest.getAccountNo());
			pibi.setBankName(payInterest.getBankName());
			pibi.setStatus("1");
			pibi.setAddBy(vo.getCode());
			pibi.setAddTime(new Date());
			payInterestDao.insertPayIntBankInfo(pibi);
		}

		CapProcessDetail cpd = capProcessManageService.queryByProcessId(processId);
		PayInterestJsonVo payIntJson = JSON.parseObject(cpd.getDetailJson(), PayInterestJsonVo.class);
		payIntJson.getInfo().setActualPayAmt(payInterest.getActualPayAmt());
		payIntJson.getInfo().setPaymentDate(payInterest.getPaymentDate());
		payIntJson.getInfo().setBankName(payInterest.getBankName());
		payIntJson.getInfo().setAccountNo(payInterest.getAccountNo());
		capProcessManageService.modifyDetailJsonById(cpd);
		return RspVo.getSuccessResponse();
	}
}